#! /usr/bin/env python

# config helpers
#
# Copyright (C) 2011-2012 Christian T. Steigies <steigies@physik.uni-kiel.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"


import os
import sys

# http://wiki.python.org/moin/OptParse
import optparse

# http://wiki.python.org/moin/ConfigParserExamples
import ConfigParser

import datetime

## --------------------------------------------------------------------------
def ParseOptions(mode="write"):

    parser = optparse.OptionParser("usage: %prog [options] [station]")
    parser.add_option("-f", "--file", dest="rcfile", default=os.environ["HOME"]+"/.nmdbrc", type="string", help="config file for NMDB")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="make lots of noise")

    if mode == "sql":
        parser.add_option("-D", "--datadir", dest="datadir", default="/var/tmp/nmdb/", type="string", help="specify data directory for sqlite files")

    if mode == "write":
        parser.add_option("-H", "--host", dest="hostname", default="db01.nmdb.eu", type="string", help="specify hostname to run on")
    elif mode == "read":
        parser.add_option("-H", "--host", dest="hostname", default="db03.nmdb.eu", type="string", help="specify hostname to run on")
    else:
        parser.add_option("-H", "--host", dest="hostname", default="db04.nmdb.eu", type="string", help="specify hostname to run on")

    parser.add_option("-P", "--port", dest="portnum", default=3306, type="int", help="port number to run on")

    parser.add_option("-u", "--update", action="store_true", dest="update", default=False, help="update (overwrite) data")
    parser.add_option("-i", "--immediate", action="store_true", dest="immediate", default=False, help="INSERT data immediately instead of DELAYED")
    parser.add_option("-t", "--startdatetime", dest="tstart", default="2000-01-01 00:00:00", type="string", help="start datetime \"yyyy-mm-dd HH:MM:SS\" to use when updating data")
    parser.add_option("-p", "--stopdatetime", dest="tstopp", type="string", help="stop datetime \"yyyy-mm-dd HH:MM:SS\" to use when updating data")
    parser.add_option("-s", "--show", action="store_true", dest="show", default=False, help="only show the last datapoint")
    parser.add_option("-c", "--count", dest="tcount", type="string", help="count data for \"yyyy-mm-dd HH:MM:SS\" day in specified table")
    parser.add_option("-n", "--dry-run", action="store_true", dest="dryrun", default=False, help="print the commands that would be executed, but do not execute them")
    parser.add_option("-m", "--max", dest="maxcount", default=120, type="int", help="max number of datapoints to send")
    parser.add_option("-0", "--nullok", action="store_true", dest="nullok", default=False, help="also send NULL values to NMDB")
   
    
    (options, args) = parser.parse_args()

    return (options, args)

## --------------------------------------------------------------------------
def ConfigSectionMap(section,Config):

    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
            dict1[option] = Config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

## --------------------------------------------------------------------------
def ParseConfig(rcfile, station, mode="nmdb"):
    """get username and password from .nmdbrc file
    (instead of storing them in the code)
    """
    
    Config = ConfigParser.ConfigParser()
    try:
        Config.read(rcfile)
    except:
        print "ParseConfig: rcfile not found:", rcfile
        sys.exit(0)

    try:
        # credentials for nmdadb data is stored in nmdbrc as kiel2_nmdadb station
        if mode == "nmdadb":
            station = station + "_" + mode

        username = ConfigSectionMap(station,Config)['username']
        password = ConfigSectionMap(station,Config)['password']

        # nmdadb mode stores information on MySQL server, options are used only for NMDB server
        if mode == "nmdadb":
            hostname   = ConfigSectionMap(station,Config)['hostname']
            dbname     = ConfigSectionMap(station,Config)['dbname']
            portnumber = ConfigSectionMap(station,Config)['port']
            return(username,password,hostname,dbname,int(portnumber))

        # perhaps change this to "download" mode?
        if station == "download":
            longname = "download"
        else:
            longname = ConfigSectionMap(station,Config)['longname']
        
        return(username,password,longname)

    except ConfigParser.NoSectionError:
        print "config for station %s not found in %s" %(station, rcfile)
        sys.exit(0)

## --------------------------------------------------------------------------
def ParseArgs(options, args, mode="write"):
    
    # determine station name
    if len(args) > 0:
        station = args[0]
        STATION=station.upper()
    else:
        raise ValueError # no station given

    # determine NMDB table to be used
    if len(args) > 1:
        table = args[1]
    else:
        table = "ori"
        
    if mode == "write":
    ## determine query string
        if options.immediate:
            qinsert = "INSERT INTO"
        else:
            qinsert = "INSERT DELAYED INTO"
            # columns ordered as in NMDB: datetime, 60, uncorr, corr_e, corr_p, pressure_mbar
        if table == "ori":
            query = "%s %s_ori (start_date_time,length_time_interval_s,measured_uncorrected,measured_corr_for_efficiency,measured_corr_for_pressure,measured_pressure_mbar)" %(qinsert, STATION)
            delta_t = datetime.timedelta(minutes=1)
        elif table == "1h":
            query = "%s %s_1h (start_date_time,uncorrected,corr_for_efficiency,corr_for_pressure,pressure_mbar)" %(qinsert, STATION)
            delta_t = datetime.timedelta(hours=1)
        elif table == "env":
            raise ValueError # env not yet implemented
        elif table == "meta":
            raise ValueError # meta not yet implemented
        else:
            print "invalid table selected: ", table
            raise ValueError

    elif mode == "read":
        if table == "ori":
            #query = "SELECT start_date_time,length_time_interval_s,measured_uncorrected,measured_corr_for_efficiency,measured_corr_for_pressure,measured_pressure_mbar FROM %s_ori" %(STATION)
            query = "SELECT start_date_time,measured_corr_for_efficiency FROM %s_ori" %(STATION)
            delta_t = datetime.timedelta(minutes=1)
        elif table == "1h":
            #query = "SELECT start_date_time,uncorrected,corr_for_efficiency,corr_for_pressure,pressure_mbar FROM %s_1h" %(STATION)
            query = "SELECT start_date_time,corr_for_efficiency FROM %s_1h" %(STATION)
            delta_t = datetime.timedelta(hours=1)
            
    else:
        query = "SELECT"
        delta_t = datetime.timedelta(minutes=1)

    if len(args) > 2:
        print "extra args not yet supported", args[2:]
        sys.exit(1)

    print "ParseArgs:", station, table, query, delta_t
    return(station, table, query, delta_t)

## --------------------------------------------------------------------------

if __name__=="__main__":
    """usage:
             python tools/configtool.py -v -f nmwbrc mcmu
    """
    print "This is the tools.configtool module."

    (options,args) = ParseOptions()
    print "options:", options
    print "args:", args
    rcfile = options.rcfile
    
    station = args[0]
    (username,password,longname) = ParseConfig(rcfile, station)
    print username
    print password
    print longname
